package com.example.interview.clone;


/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-04-01
 * Time:21:02
 * Text：
 */
class Teacher  implements Cloneable{
    private String name;
    private  int age;
    private Student student;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    protected Teacher clone(){
        Teacher t1 = null;
        try {
            t1 = (Teacher) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
        return t1;
    }
}
class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
public class Test1 {

    public static void Shallow_cloning(){
        Teacher teacher = new Teacher();
        teacher.setAge(19);
        teacher.setName("李华");
        Student student = new Student();
        student.setName("喜喜");
        teacher.setStudent(student);

        Teacher teacher1 = teacher.clone();
        System.out.println("浅克隆：");
        System.out.println("外层是否相等:"+(teacher1 == teacher));
        System.out.println("内层是否相等:"+(teacher1.getStudent() == teacher.getStudent()));
    }
    //深克隆方法一：使用 JSON 工具
    public void Deep_Clone2(){
        Teacher teacher = new Teacher();
        teacher.setAge(19);
        teacher.setName("李华");
        Student student = new Student();
        student.setName("喜喜");
        teacher.setStudent(student);

//        // JSON 工具类
//        Gson gson = new Gson();
//        // 序列化
//        String json = gson.toJson(teacher);
//        // 克隆 p1 对象 | 反序列化
//        Teacher p2 = gson.fromJson(json, Person.class);
//        // 对比引用类型的地址值是否相同
//        System.out.println(p1.getAddress() == p2.getAddress()); //false

    }

}
